<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\TCourseSigninInfo;
use app\models\TCourseSigninStudent;
use app\common\ArrayHelper;
use app\models\TCourseMember;
use app\models\TCourseInfo;
use app\models\TCourseEvaluate;
use Faker\Provider\Uuid;

class ClassroomteacherController extends Controller
{
    public $enableCsrfValidation = false;

    public function init()
    {
        parent::init();
        header('Access-Control-Allow-Origin: *');
    }

    /**
     * 微信小程序获取课表列表接口
     * @param string userId:用户ID
     * @return mixed 错误返回json，正确返回json
     * @date: 2020-04-02
     * @author: gyq
     */
    public function actionAppGetScheduleList()
    {
        $error = array();
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $time = isset($_REQUEST['time']) ? $_REQUEST['time'] : date('Y-m-d', time());
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => [],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            //一年内有课表的日期集合
            $startdate = (date('Y')-1).'-'.date('m-d');
            $enddate = (date('Y')+1).'-'.date('m-d');
            $date = self::getDateFromRange($startdate,$enddate);
            $new_array = [];
            foreach($date as $k=>$v){
                $times=self::getTime(strtotime($v));
                $sql = "SELECT
	b.id
FROM
	t_course_schedule b
LEFT JOIN t_course_teacher a ON a.course_id = b.t_course_id
WHERE a.teacher_id=:userId AND UNIX_TIMESTAMP(b.begin_time) BETWEEN :star AND :ends AND a.del_flag=0 AND b.del_flag=0";
                $corseList = Yii::$app->db->createCommand($sql)->bindValues([':userId' => $userId, ':star' => $times['star'], ':ends' => $times['end']])->queryOne();
                if ($corseList) {
                    $new_array[]['date'] =$v;
                }
            }
            $d_time = self::getTime(strtotime($time));
            $sql = "SELECT 
b.id,
b.schedule_name,
b.t_course_id,
i.name as course_name,
i.b_course_info_id,
i.project_id,
b.begin_time,
c.t_course_item_id,
c.t_course_item_pid 
FROM t_course_teacher a 
LEFT JOIN t_course_schedule b ON a.course_id=b.t_course_id
LEFT JOIN t_course_info i ON b.t_course_id=i.id
LEFT JOIN t_course_schedule_chapter c ON c.t_course_schedule_id=b.id
WHERE 
a.teacher_id=:userId 
AND UNIX_TIMESTAMP(b.begin_time) 
BETWEEN :star 
AND :ends 
AND a.del_flag=0 
AND b.del_flag=0 
ORDER BY b.begin_time ASC";
            $scheduleList = Yii::$app->db->createCommand($sql)->bindValues([':userId' => $userId, ':star' => $d_time['star'], ':ends' => $d_time['end']])->queryAll();
            if ($scheduleList) {
                foreach ($scheduleList as $k => &$v) {
                    $sql = "select title from t_course_item where id='" . $v['t_course_item_pid'] . "'";
                    $chapter = \Yii::$app->db->createCommand($sql)->queryScalar();
                    $sql = "select title from t_course_item where id='" . $v['t_course_item_id'] . "'";
                    $jie = \Yii::$app->db->createCommand($sql)->queryScalar();
                    $chapter_str = $chapter . '>>' . $jie;
                    $v['zhang_jie'] = $chapter_str;
                    //班级名称
                    $sql = "SELECT
	c.class_name,c.id as class_id
FROM
	t_base_class c
LEFT JOIN t_course_schedule_class sc ON sc.class_id = c.id
WHERE
	sc.t_course_schedule_id =:schedule_id";
                    $classInfo = \yii::$app->db->createCommand($sql)->bindValues([':schedule_id' => $v['id']])->queryAll();
                    $str = "";
                    $classIds = "";
                    foreach ($classInfo as $key => $value) {
                        $str .= $value['class_name'] . ",";
                        $classIds .= $value['class_id'] . ",";
                    }
                    $v['class_name'] = rtrim($str, ',');
                    $v['class_id'] = rtrim($classIds, ',');
                }
                $data['existenceSchedule'] = $new_array;
                $data['todayslesson'] = $scheduleList;
                $data['nowTime'] = date('Y-m-d', time());
                $result = [
                    'msg' => '查询成功',
                    'ver' => '1.5.0',
                    'data' => $data,
                    'code' => '200'
                ];
            } else {
                $result = [
                    'msg' => '没有查询到相关数据',
                    'ver' => '1.5.0',
                    'data' => ['existenceSchedule' => $new_array, 'todayslesson' => [], 'nowTime' => date('Y-m-d', time())],
                    'code' => '200'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 获取指定日期段内每一天的日期
     * @param  Date  $startdate 开始日期
     * @param  Date  $enddate   结束日期
     * @return Array
     */

    public static  function  getDateFromRange($startdate, $enddate){
        $stimestamp = strtotime($startdate);
        $etimestamp = strtotime($enddate);

        // 计算日期段内有多少天
        $days = ($etimestamp-$stimestamp)/86400+1;
        // 保存每天日期
        $date = array();

        for($i=0; $i<$days; $i++){
            $date[] = date('Y-m-d', $stimestamp+(86400*$i));
        }
        return $date;
    }
    /**
     * 微信小程序课程预习学习复习列表接口
     * @param int  courseId:课程ID userId:用户ID projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2020-04-02
     * @author: gyq
     */
    public function actionAppGetScheduleInfo()
    {
        $error = array();
        $tcourseId = isset($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error[] = array('课程ID不能为空');
        $scheduleId = !empty($_REQUEST['scheduleId']) ? $_REQUEST['scheduleId'] : $error[] = array('ID不能为空');
        $userId = !empty($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        $type = !empty($_REQUEST['type']) ? $_REQUEST['type'] : $error[] = array('类型不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => [],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $info_arr = array();
            $sql = "select tcsr.resource_id as id,tcsr.item_id,c.title,tcsr.file_id,trf.uri,trf.type as file_type,tcsr.create_time,tcsr.times,trf.mime as mime_type from t_course_schedule_resource tcsr left join t_resource_file trf on trf.id=tcsr.file_id left join t_course_item_resource_reference c on c.resourse_id=tcsr.resource_id and c.item_id=tcsr.item_id where tcsr.t_course_schedule_id=:scheduleId and tcsr.t_course_id=:courseId and tcsr.type=:type";
            $resourceList = \Yii::$app->db->createCommand($sql)
                ->bindValue(':scheduleId', $scheduleId)
                ->bindValue(':courseId', $tcourseId)
                ->bindValue(':type', $type)
                ->queryAll();

            foreach ($resourceList as $k => &$resource) {
                if (in_array($resource['mime_type'], ['resourceType.document', 'resourceType.ppt'])) {
                    $resource['docConvert'] = true;
                    $fileBaseUrl = \Yii::$app->params['fileUrlWeiXin'];
                    $resource['uri'] = $fileBaseUrl . (empty($resource) ? '' : $resource['uri']);
                } else {
                    $resource['docConvert'] = false;
                    $resource['uri'] = \yii::$app->params['fileUrlWeiXin'] . $resource['uri'];
                }
//                $sql="select current_progress,type from t_course_items_video_current where item_id=:itemId and resource_id=:resourceId and user_id=:userId and del_flag=0";
//                $info=\yii::$app->db->createCommand($sql)->bindValues([
//                    ':itemId'=>$resource['item_id'],
//                    ':resourceId'=>$resource['id'],
//                    ':userId'=>$userId,
//                ])->queryOne();
//                if($info['type']=='progressType.video'){
//                    $sql="SELECT
//	trf.play_time
//FROM
//	t_resource_file trf
//LEFT JOIN t_resource_info tri ON trf.id = tri.file_id
//WHERE
//	tri.id =:resourceId";
//                    $play_time=\yii::$app->db->createCommand($sql)->bindValues([':resourceId'=>$resource['id']])->queryScalar();
//                    $t = explode(':',$play_time);
//                    $totalTime=$t[0] * 3600 + $t[1]*60+$t[2];//假定最长视频十二小时
//                    $progress=round(($info['current_progress']/$totalTime)*100);
//                }else{
//                    //非视频音频类型
//                    $progress=empty($info['current_progress']) ? 0 : 100 ;
//                }
                //进度不能大于100
//                $progress=($progress>100)?100:$progress;
                if (in_array($resource['file_type'], ['doc', 'docx'])) {
                    $icon = "/weixin/resources/01.png";
                } elseif (in_array($resource['file_type'], ['png', 'jpg', 'jpeg', 'JPG', 'PNG', 'JPEG', 'bmp', 'gif'])) {
                    $icon = "/weixin/resources/02.png";
                } elseif (in_array($resource['file_type'], ['xls', 'xlsx'])) {
                    $icon = "/weixin/resources/03.png";
                } elseif ($resource['file_type'] == 'pdf') {
                    $icon = "/weixin/resources/04.png";
                } elseif ($resource['file_type'] == 'txt') {
                    $icon = "/weixin/resources/05.png";
                } elseif (in_array($resource['file_type'], ['ppt', 'pptx'])) {
                    $icon = "/weixin/resources/06.png";
                } elseif ($resource['file_type'] == 'swf') {
                    $icon = "/weixin/resources/07.png";
                } elseif (in_array($resource['file_type'], ['html', 'htm'])) {
                    $icon = "/weixin/resources/08.png";
                } elseif (in_array($resource['file_type'], ['ogg', 'ogv', 'mov', 'webm', 'mp3', 'wav', 'mid'])) {
                    $icon = "/weixin/resources/09.png";
                } else if (in_array($resource['file_type'], ['flv', 'mkv', 'avi', 'rm', 'rmvb', 'mp4', 'wmv'])) {
                    $icon = "/weixin/resources/10.png";
                } else {
                    $icon = "/weixin/resources/11.png";
                }
                $resource['icon'] = \yii::$app->params['interFaceWeiXin'] . $icon;
//                $resource['progress']=$progress;
                $info_arr[] = $resource;
            }
            if ($info_arr) {
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'data' => $info_arr,
                    'success' => true,
                    'code' => '200'
                ];
            } elseif (empty($info_arr)) {
                $result = [
                    'msg' => '没有查询到相关数据',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '200'
                ];
            } elseif ($info_arr === false) {
                $result = [
                    'msg' => '查找失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }

    //课堂教学已导入素材列表
    public function actionResourceList()
    {
        $courseId = $_REQUEST['course_id'];
        $scheduleId = $_REQUEST['schedule_id'];
        $type = $_REQUEST['type'];
        $resourceList = [];
        $sql = "select * from t_course_schedule_resource csr where csr.t_course_id=:cid and csr.t_course_schedule_id=:sid and csr.type=:type and csr.del_flag=0 ";
        $list = \Yii::$app->db->createCommand($sql)->bindValue(':sid', $scheduleId)->bindValue(':type', $type)->bindValue(':cid', $courseId)->queryAll();
        $total=0;
        $sql="select class_id from t_course_schedule_class where del_flag=0 and t_course_schedule_id=:schedule_id";
        $classIds=\yii::$app->db->createCommand($sql)->bindValues([':schedule_id'=>$scheduleId])->queryColumn();
        if(!empty($classIds)){
            $cids="";
            foreach($classIds as $k1=>$v1){
                $cids.="'".$v1."',";
            }
            $cids=rtrim($cids,',');
            $sql="select count(*) from t_course_member where course_id = :tcourseid and class_id in (".$cids.") and del_flag=0";
            $total = \app\models\TCourseMember::findBySql($sql,[':tcourseid'=>$courseId])->scalar();
        }
        foreach ($list as $m) {
            $sql = "select tirr.title,tirr.create_time from t_course_item_resource_reference tirr where tirr.resourse_id=:rid and tirr.item_id=:tid and tirr.del_flag=0";
            $tirr = Yii::$app->db->createCommand($sql)->bindValue(':rid', $m['resource_id'])->bindValue(':tid', $m['item_id'])->queryOne();
            $file = "select size,type,uri,mime from t_resource_file where id=:id";
            $fileInfo = \Yii::$app->db->createCommand($file)->bindValue(':id', $m['file_id'])->queryOne();
            if (in_array($fileInfo['mime'], array('resourceType.document', 'resourceType.ppt'))) {
                $url = \Yii::$app->params['docConvertUrl'] . '&furl=' . \Yii::$app->params['fileUrl'] . $fileInfo['uri'];
            } else {
                $url = \Yii::$app->params['fileUrl'] . $fileInfo['uri'];
            }
            $arr = array('title' => $tirr['title'], 'url' => $url, 'time' => $m['create_time'], 'resourceId' => $m['resource_id'], 'size' => self::getSize($fileInfo['size']), 'resourceType' => $fileInfo['mime']);
            if (in_array($fileInfo['type'], ['doc', 'docx'])) {
                $icon = "/weixin/resources/01.png";
            } elseif (in_array($fileInfo['type'], ['png', 'jpg', 'jpeg', 'JPG', 'PNG', 'JPEG', 'bmp', 'gif'])) {
                $icon = "/weixin/resources/02.png";
            } elseif (in_array($fileInfo['type'], ['xls', 'xlsx'])) {
                $icon = "/weixin/resources/03.png";
            } elseif ($fileInfo['type'] == 'pdf') {
                $icon = "/weixin/resources/04.png";
            } elseif ($fileInfo['type'] == 'txt') {
                $icon = "/weixin/resources/05.png";
            } elseif (in_array($fileInfo['type'], ['ppt', 'pptx'])) {
                $icon = "/weixin/resources/06.png";
            } elseif ($fileInfo['type'] == 'swf') {
                $icon = "/weixin/resources/07.png";
            } elseif (in_array($fileInfo['type'], ['html', 'htm'])) {
                $icon = "/weixin/resources/08.png";
            } elseif (in_array($fileInfo['type'], ['ogg', 'ogv', 'mov', 'webm', 'mp3', 'wav', 'mid'])) {
                $icon = "/weixin/resources/09.png";
            } else if (in_array($fileInfo['type'], ['flv', 'mkv', 'avi', 'rm', 'rmvb', 'mp4', 'wmv'])) {
                $icon = "/weixin/resources/10.png";
            } else {
                $icon = "/weixin/resources/11.png";
            }
            $arr['icon'] = \yii::$app->params['interFaceWeiXin'] . $icon;
            //播放情况
            $looked=0;
            if(!empty($classIds)){
                $sql="select count(*) from t_course_member where course_id = :tcourseid and class_id in (".$cids.") and del_flag=0";
                $total = \app\models\TCourseMember::findBySql($sql,[':tcourseid'=>$courseId])->scalar();
                $sql = "SELECT count(distinct c.user_id) FROM `t_course_items_video_current` c
                        LEFT JOIN `t_base_user_profile` p ON `p`.`user_id` = `c`.`user_id`
                        LEFT JOIN `t_course_member` m ON `m`.`user_id` = `c`.`user_id`
                        WHERE c.`course_id` = :tcourseid 
                            AND `resource_id` =:rid 
                            AND `m`.`class_id` in (".$cids.")
                            AND `m`.`del_flag` = 0";
                $looked = \app\models\TCourseItemsVideoCurrent::findBySql($sql,[':tcourseid'=>$courseId,':rid'=>$m['resource_id']])->scalar();
            }
            $arr['totalNum']=$total;
            $arr['looked']=$looked;
            $resourceList[] = $arr;
        }
        if (!empty($resourceList)) {
            $result = array(
                "msg" => "查询成功",
                "ver" => "1.5.0",
                'data' => $resourceList,
                'code' => '200'
            );
        } else {
            $result = array(
                "msg" => "没有查询到相关数据",
                "ver" => "1.5.0",
                'data' => [],
                'code' => '404'
            );
        }
        Yii::$app->end(json_encode($result));
    }

    //课表资源列表--添加_章
    public function actionChapterList()
    {
        $courseId = $_REQUEST['course_id'];
        $sql = "select id,title as name,pid as pId,'directory' as type,1 as level,create_by from t_course_item "
            . "where course_id=:courseId and del_flag=0 and pid='0' order by sequence asc";
        $catalogList = Yii::$app->db->createCommand($sql)->bindValues([':courseId' => $courseId])->queryAll();
        if (!empty($catalogList)) {
            $result = array(
                "msg" => "查询成功",
                "ver" => "1.5.0",
                'data' => $catalogList,
                'code' => '200'
            );
        } else {
            $result = array(
                "msg" => "没有查询到相关数据",
                "ver" => "1.5.0",
                'data' => [],
                'code' => '200'
            );
        }
        Yii::$app->end(json_encode($result));
    }

    //课表资源列表--添加_节
    public function actionSectionList()
    {
        $schedule_id = $_REQUEST['schedule_id'] = 'ac318575-601d-354a-b6e7-59222f3fd8ac';
        $chapterId = $_REQUEST['chapter_id'] = '5e0cacf1-7262-37df-8a11-4b73e4815ee1';//小节id
        $courseId = $_REQUEST['course_id'] = 'addd07a4-c10c-3612-b7cf-e996473f2be2';
        $type = $_REQUEST['type'] = 'directory';//课前 课中 课后
        $sql = "select birr.id as id,birr.item_id as pId,birr.title as name,'file' as type,2 as level,birr.sequence,tri.id as resourceId,birr.create_by,birr.create_time,f.mime,f.size,f.uri as url,f.id as fileId "
            . "from t_course_item_resource_reference birr "
            . "left join t_resource_info tri on tri.id=birr.resourse_id "
            . "left join t_resource_file f on f.id = tri.file_id "
            . "where item_id=:item_id and birr.course_id=:course_id and birr.del_flag=0";
        $resourceList = Yii::$app->db->createCommand($sql)->bindValues([':item_id' => $chapterId, ':course_id' => $courseId])->queryAll();
        $sql = "select id,pid as pId,title as name,'directory' as type,2 as level,sequence,create_by,'' as szie,'' as url from t_course_item "
            . "where pid=:pid and course_id=:courseId and del_flag =0";
        $sectionList = Yii::$app->db->createCommand($sql)->bindValues([':pid' => $chapterId, ':courseId' => $courseId])->queryAll();
        $erjiList = self::array_sort(array_merge($resourceList, $sectionList), 'sequence');
        $selected = \app\models\TCourseScheduleResource::find()
            ->where('t_course_schedule_id=:schedule and t_course_id=:tid and type=:type and del_flag=0', [':schedule' => $schedule_id, ':tid' => $courseId, ':type' => $type])->select('resource_id')->asArray()->column();
        foreach ($erjiList as &$ej) {
            if ($ej['type'] == 'file') {
                $ej['size'] = self::getSize($ej['size']);
                if (in_array($ej['mime'], array('resourceType.document', 'resourceType.ppt'))) {
                    $ej['url'] = \Yii::$app->params['docConvertUrl'] . '&furl=' . \Yii::$app->params['fileUrl'] . $ej['url'];
                } else {
                    $ej['url'] = \Yii::$app->params['fileUrl'] . $ej['url'];
                }
                $ej['selected'] = in_array($ej['resourceId'], $selected) ? true : false;
            }
        }
        $result = array(
            "msg" => "查询成功",
            "ver" => "1.5.0",
            'data' => $erjiList,
            'code' => '200'
        );
        Yii::$app->end(json_encode($result));
    }

    //导入素材接口
    public function actionSaveCourseware()
    {
        $tcourseId = $_REQUEST['course_id'];
        $schedule_id = $_REQUEST['schedule_id'];
        $ids = $_REQUEST['ids'];
        $type = $_REQUEST['type'];//课前课中课后
        $uid = $_REQUEST['uid'];
        $number = 0;
        $datas = \app\common\ArrayHelper::toArray(json_decode($ids));
        foreach ($datas as $value) {
            $model = new \app\models\TCourseScheduleResource();
            $model->id = \Faker\Provider\Uuid::uuid();
            $model->t_course_id = $tcourseId;
            $model->t_course_schedule_id = $schedule_id;
            $model->resource_id = $value['id'];
            $model->file_id = $value['file_id'];
            $model->type = $type;
            $model->item_id = $value['item_id'];
            $model->create_by = $uid;
            $model->create_time = date('Y-m-d H:i:s', time());
            $model->del_flag = 0;
            if ($model->validate() && $model->save()) {
                $number++;
            }
        }
        $result = array(
            "msg" => "查询成功",
            "ver" => "1.5.0",
            'data' => array('sucess' => $number),
            'code' => '200'
        );
        Yii::$app->end(json_encode($result));
    }

    /**
     * 微信小程序获取签到事件接口
     * @param int  party_id:班级ID course_id:课程ID user_id:用户ID  projectId:联盟ID
     * @param string  start_time:开始时间 end_time:结束时间 code:签到码
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2020-03-04
     * @author: gyq
     */
    public function actionAppGetSigninInfo()
    {
        $error = array();
        $userId = !empty($_REQUEST['userId']) ? $_REQUEST['userId'] : $error = array('用户id不能为空');
        $courseId = !empty($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error = array('课程id不能为空');
        $scheduleId = !empty($_REQUEST['scheduleId']) ? $_REQUEST['scheduleId'] : $error = array('课表id不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => [],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $sql = "SELECT tcsi.id,tcsi.code,tcsi.start_time,tcsi.end_time,tcsi.old_id,tcss.status,tcss.code as student_code,tcss.signin_time
FROM t_course_signin_info tcsi 
LEFT JOIN t_course_signin_student tcss ON tcsi.id=tcss.sign_id
LEFT JOIN t_course_schedule_sign ss ON ss.sign_id=tcsi.id
WHERE tcsi.course_id=:courseId 
AND tcss.user_id=:userId 
AND tcsi.status=:status 
AND '" . time() . "' 
BETWEEN UNIX_TIMESTAMP(tcsi.start_time) 
AND UNIX_TIMESTAMP(tcsi.end_time) 
AND tcsi.type='signinType.common' 
AND tcsi.del_flag=0 
AND tcss.del_flag=0 
AND ss.del_flag=0
AND ss.t_course_schedule_id=:scheduleId
ORDER BY tcsi.create_time DESC limit 1";
            $params = [':courseId' => $courseId, ':userId' => $userId, ':status' => 'usingStatus.start', ':scheduleId' => $scheduleId];
            $sign = Yii::$app->db->createCommand($sql)
                ->bindValues($params)
                ->queryOne();
            //当前时间年月日星期
            $year = date('Y', time());
            $month = date('m', time());
            $day = date('d', time());
            $week = date('w', time());
            $weekarray = array("日", "一", "二", "三", "四", "五", "六");
            $timeInfo = ['year' => $year, 'month' => $month, 'day' => $day, 'week' => "星期" . $weekarray[$week]];
            if ($sign) {
                $sign['timeInfo'] = $timeInfo;
                //处理学生签到码
                if (!empty($sign['student_code']) && $sign['status'] == 'yesOrNo.yes') {
                    $first = substr($sign['student_code'], 0, 1);
                    $second = substr($sign['student_code'], 1, 1);
                    $third = substr($sign['student_code'], 2, 1);
                    $last = substr($sign['student_code'], 3, 1);
                    $sign['student_code'] = [
                        empty($first) && $first != 0 ? '' : $first,
                        empty($second) && $second != 0 ? '' : $second,
                        empty($third) && $third != 0 ? '' : $third,
                        empty($last) && $last != 0 ? '' : $last
                    ];
                }
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'data' => $sign,
                    'success' => true,
                    'code' => '200'
                ];
            } elseif (empty($sign)) {
                $result = [
                    'msg' => '已结束',
                    'ver' => '1.5.0',
                    'data' => ['id' => '', 'code' => '', 'start_time' => '', 'end_time' => '', 'timeInfo' => $timeInfo, 'signin_time' => ''],
                    'success' => false,
                    'code' => '200'
                ];
            } elseif ($sign === false) {
                $result = [
                    'msg' => '查找失败',
                    'ver' => '1.5.0',
                    'data' => ['id' => '', 'code' => '', 'start_time' => '', 'end_time' => '', 'timeInfo' => $timeInfo],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }

    /**
     * 微信小程序学生签到接口
     * @param int  userId:用户ID  projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2020-03-05
     * @author: gyq
     */
    public function actionAppDoSigninInfo()
    {
        $error = array();
        $sign_id = isset($_REQUEST['signId']) ? $_REQUEST['signId'] : $error[] = array('签到事件ID不能为空');
        $code = isset($_REQUEST['code']) ? $_REQUEST['code'] : $error[] = array('签到码不能为空');
        $user_id = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[] = array('用户ID不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $sign = TCourseSigninInfo::find()->where('id=:sign_id and del_flag=0', [':sign_id' => $sign_id])->one();
            if ($sign) {
                $time = date("Y-m-d H:i:s", time());
                if ($time > $sign->end_time || $time < $sign->start_time) {
                    $result = [
                        'msg' => '未在签到时间内',
                        'ver' => '1.5.0',
                        'data' => [],
                        'code' => '400'
                    ];
                    Yii::$app->end(json_encode($result));
                }
                $model = TCourseSigninStudent::find()->where('sign_id=:sid and user_id=:uid and del_flag=0', [':sid' => $sign_id, ':uid' => $user_id])->one();
                if (empty($model)) {
                    $result = [
                        'msg' => '没有该签到事件',
                        'ver' => '1.5.0',
                        'data' => [],
                        'success' => false,
                        'code' => '404'
                    ];
                    Yii::$app->end(json_encode($result));
                }
                $model->status = "yesOrNo.yes";
                $model->code = $code;
                $model->signin_time = date('Y-m-d H:i:s');
                $model->student_status = 'signinStatus.sign';
                $model->update_by = $user_id;
                $model->update_time = date('Y-m-d H:i:s');
                $res = $model->update();
                if ($res) {
                    $first = substr($code, 0, 1);
                    $second = substr($code, 1, 1);
                    $third = substr($code, 2, 1);
                    $last = substr($code, 3, 1);
                    $student_code = [
                        empty($first) && $first != 0 ? '' : $first,
                        empty($second) && $second != 0 ? '' : $second,
                        empty($third) && $third != 0 ? '' : $third,
                        empty($last) && $last != 0 ? '' : $last
                    ];
                    $result = [
                        'msg' => '签到成功',
                        'ver' => '1.5.0',
                        'data' => ['signin_time' => date('Y-m-d H:i:s'), 'student_code' => $student_code],
                        'success' => true,
                        'code' => '200'
                    ];
                } else {
                    $result = [
                        'msg' => '签到失败',
                        'ver' => '1.5.0',
                        'data' => [],
                        'success' => false,
                        'code' => '400'
                    ];
                }
            } else {
                $result = [
                    'msg' => '没有该签到事件',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '404'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }

    /**
     * 获取今天的开始和结束时间
     * @return mixed
     */
    public static function getTime($time)
    {
        $str = date("Y-m-d", $time) . " 0:0:0";
        $data["star"] = strtotime($str);
        $str = date("Y-m-d", $time) . " 24:00:00";
        $data["end"] = strtotime($str);
        return $data;
    }

    public static function get_week($time = '', $format = 'd')
    {
        $time = $time != '' ? $time : time();
        //获取当前周几
        $week = date('w', $time);
        $str = date('d', $time);
        for ($i = 1; $i <= 7; $i++) {
            $str .= ',' . date($format, strtotime('+' . $i - $week . ' days', $time));
        }
        return trim($str, ',');
    }

    public static function array_sort($arr, $keys, $type = 'asc')
    {
        $keysvalue = $new_array = array();
        foreach ($arr as $k => $v) {
            $keysvalue[$k] = $v[$keys];
        }
        if ($type == 'asc') {
            asort($keysvalue);
        } else {
            arsort($keysvalue);
        }
        reset($keysvalue);
        foreach ($keysvalue as $k => $v) {
            $new_array[] = $arr[$k];
        }
        return $new_array;
    }

    public static function getSize($size)
    {
        $str = '';
        if ($size > 1024 * 1024) {
            $str = mb_substr(empty($size) ? 0 : $size / 1024 / 1024, 0, strrpos(empty($size) ? 0 : $size / 1024 / 1024, '.') + 3) . "MB";
        } elseif ($size > 1024) {
            $str = mb_substr(empty($size) ? 0 : $size / 1024, 0, strrpos(empty($size) ? 0 : $size / 1024, '.') + 3) . "KB";
        } else {
            $str = $size . 'b';
        }
        return $str;
    }
}
?>